package hpp.meitu;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2017/9/5.
 */
public class MeiTuTest {

    public static void main(String[] args) {

//        taskOne();
        taskTwo();
    }

    //生成文件
    public static void taskOne() {

        int Max = 10;
        // 线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        //设置信号量同时执行的线程数是5
        final Semaphore semp = new Semaphore(5);
        // 模拟20个客户端访问
        for (int index = 0; index < 10; index++) {
            final int NO = index;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        //使用acquire()获取锁
                        semp.acquire();
                        GenerateFiles.gernerateFiles(Thread.currentThread().getName(), Max);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        //使用完成释放锁
                        semp.release();
                    }
                }
            };
            exec.execute(run);
        }
        // 退出线程池
        exec.shutdown();
    }

    public static void taskTwo() {

        Map<Integer, Integer> map = new HashMap<>();
        List<Future<Map<Integer, Integer>>> list = new LinkedList<>();
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            Future<Map<Integer, Integer>> future = executorService.submit(new Count("E:\\meituTestFiles\\in\\pool-1-thread-" + (i + 1) + ".txt"));
            list.add(future);
        }
        executorService.shutdown();
        //统计
        try {
            for (Future<Map<Integer, Integer>> item : list) {
                Map<Integer, Integer> tmpMap = item.get();
                for (Map.Entry<Integer, Integer> entry : tmpMap.entrySet()) {
                    if (map.containsKey(entry.getKey())) {
                        map.put(entry.getKey(), map.get(entry.getKey()) + entry.getValue());
                    } else {
                        map.put(entry.getKey(), entry.getValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }






}
